<?php
/**
 * Created by PhpStorm.
 * User: front
 * Date: 2018/8/3
 * Time: 16:39
 */

namespace App\Services;

use App\Exceptions\ApiException;
use OSS\Core\OssException;
use OSS\OssClient;
use Sts\Request\V20150401\AssumeRoleRequest;

class Sts
{
    static $data;

    /**
     * 获取Oss upload token
     * @return array
     * @throws ApiException
     */
    public static function getData($duration = 0)
    {
        include_once base_path('public/sts-server/aliyun-php-sdk-core/Config.php');

        $accessKeyID = env('ACCESS_KEY_ID');
        $accessKeySecret = env('ACCESS_KEY_SECRET');
        $roleArn = env('ROLE_ARN');
        $tokenExpire = $duration ? $duration : env('TOKEN_EXPIRE_TIME');
        $policy = self::readFile(base_path(env('POLICY_FILE')));

        $iClientProfile = \DefaultProfile::getProfile('cn-hangzhou', $accessKeyID, $accessKeySecret);
        $client = new \DefaultAcsClient($iClientProfile);

        $request = new AssumeRoleRequest();
        $request->setRoleSessionName("client_name");
        $request->setRoleArn($roleArn);
        $request->setPolicy($policy);
        $request->setDurationSeconds($tokenExpire);
        $response = $client->doAction($request);

        $rows = array();
        $body = $response->getBody();
        $content = json_decode($body);
        if ($response->getStatus() == 200)
        {
            $rows['AccessKeyId'] = $content->Credentials->AccessKeyId;
            $rows['AccessKeySecret'] = $content->Credentials->AccessKeySecret;
            $rows['Expiration'] = $content->Credentials->Expiration;
            $rows['SecurityToken'] = $content->Credentials->SecurityToken;
            $rows['bucketName'] = env('BUCKET_NAME');
            $rows['endpoint'] = env('STS_ENDPOINT');
        }
        else
        {
            throw new ApiException($content->Message, 0);
        }

        return $rows;
    }

    public static function getSignUrl($object = '', $duration = 0, $bucketName = '')
    {
        if (!self::$data) {
            self::$data = self::getData($duration);
        }

        $accessKeyId = self::$data['AccessKeyId'];
        $accessKeySecret = self::$data['AccessKeySecret'];
        $endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
        $bucket = $bucketName === '' ? env('BUCKET_NAME') : $bucketName;
        $securityToken = self::$data['SecurityToken'];

        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
            // 生成GetObject的签名URL。
            $signedUrl = $ossClient->signUrl($bucket, $object, $duration);
        } catch (OssException $e) {
            return json_error($e->getMessage());
        }

        return $signedUrl;
    }

    /**
     * 读取文件内容
     * @param string $fname
     * @return string
     * @throws ApiException
     */
    public static function readFile($fname)
    {
        $content = '';
        if (!file_exists($fname)) {
            throw new ApiException("The file $fname does not exist", 0);
        }
        $handle = fopen($fname, "rb");
        while (!feof($handle)) {
            $content .= fread($handle, 10000);
        }
        fclose($handle);
        return $content;
    }

    /*
     * 上传文件
     *
     * $filePath 文件路径
     * $object 存储oss 路径
     * */
    public static function fileUpload($filePath, $object)
    {
        $accessKeyId = env('WEB_ACCESS_ID');
        $accessKeySecret = env('WEB_ACCESS_KEY');
        $endpoint = "http://".env('WEB_ENDPOINT');
        // 存储空间名称
        $bucket= env('WEB_BUCKET_NAME');

        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $response = $ossClient->uploadFile($bucket, $object, $filePath);

            if($response['info' ]['http_code'] != '200')
                return ['status'=>'error', 'message_code'=>10160, 'message'=>'上传失败', 'data'=>$response];
            return ['status'=>'success', 'message_code'=>10161, 'message'=>'上传成功', 'data'=>$response];

        } catch(OssException $e) {
            return ['status'=>'error', 'message'=>$e->getMessage()];
        }
    }
}